package br.com.bolsamovel;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;


public class DateUtils {
    public static final long MILLISECS_PER_MINUTE = 60*1000;
    public static final long MILLISECS_PER_HOUR   = 60*MILLISECS_PER_MINUTE;
    protected static final long MILLISECS_PER_DAY = 24*MILLISECS_PER_HOUR;

	public static String formatAsDate(long date){
		String asStr = String.valueOf(date);
		
		int year = Integer.parseInt(asStr.substring(0, 4));
		int month = Integer.parseInt(asStr.substring(4, 6));
		int day = Integer.parseInt(asStr.substring(6, 8));
		
		StringBuffer b = new StringBuffer();
		
		b.append(day < 10 ? "0" : "").append(day).append('/').append(month < 10 ? "0" : "").append(month).append('/').append(year);
		
		
		return b.toString();
	}
	
	public static Date asDate(long l, String format){
		try{
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			return sdf.parse(String.valueOf(l));
		}catch (Exception e) {
			UIUtils.throwsNonChecked(e);
		}
		return null;
	}
	
	public static int diff(long dt1, long dt2){
		Calendar c1 = buildCalendar(dt1);
		Calendar c2 = buildCalendar(dt2);

		long end = c2.getTimeInMillis() + c2.getTimeZone().getOffset(c2.getTimeInMillis());
		long start = c1.getTimeInMillis() + c1.getTimeZone().getOffset(c1.getTimeInMillis());
		
		return Math.abs((int)((end-start) / MILLISECS_PER_DAY));
	}
	
	private static Calendar buildCalendar(long dt1){
		int year = (int)dt1/10000;
		int month = ((int)dt1/100) - (((int)dt1/10000)*100);
		int day = (int)(dt1 - (((int)dt1/100)*100) );

		Calendar c = new GregorianCalendar();
		c.clear();
		
		c.set(Calendar.YEAR, year);
		c.set(Calendar.MONTH, month-1);
		c.set(Calendar.DAY_OF_MONTH, day);
		
		return c;
	}

}
